LintCode-91. Minimum Adjustment Cost
Description
Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
You can assume each number in the array is a positive integer and not greater than 100
.
Example
Given [1,4,2,3]
and target = 1
, one of the solutions is [2,3,2,3]
, the adjustment cost is 2
and it’s minimal.
Return 2
.
Analyst:
题目:对 A[i]
进行调整, A[i] -> B[i]
,
使得:
| B[i] - B[i-1] |<= target
Sum{|A[i] - B[i]|}
值最小, 求最小Sum{|A[i] - B[i]|}
最后一步:
F[k]
表示到 第k-1
个数的总调整数result
。1)需要调整,调整总和
F[k] = F[k-1] + min (A[k] + target - A[k-1] || A[k] - target - B[k-1] ) ) ( |A[k] - B[k-1]| > target )
2) 不需要调整,
F[k] = F[k-1] ( |A[k] - A[k-1]| <= target )
因为这里用到调整后的
A[k-1]
,我们把A[k-1]
记做m
保存在A[k][m]
上,表示每当我们走到A[k-1]
,并且吧这个数变成了m
因此,以上式子变成
F[k][m]
表示,走到A[k-1]
时, 把A[k-1]
变成m
是的总调整数F[k][m] = min (F[k][m], F[k-1][n] + abs(A[k-1]- m))
顺序从小到大
初始状态, 边界情况
F[1][j] = 0
Code
1 | public class Solution { |